package com.jamaskii.ecdict;

import com.jamaskii.dictation.HomeActivity;
import com.jamaskii.utils.IOUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;

public class Word {
    public String name;
    public String translated;
    public boolean chinese;

    public Word() {
        this.chinese = false;
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }

    public Word(String name, String translated) {
        this.name = name;
        this.translated = translated;
        this.chinese = true;
    }

    public String dumps(){
        if(name==null){
            return null;
        }else if(translated==null){
            return null;
        }else{
            return name+"="+translated.replace("\n", "#gap#")+"="+ (chinese?"C":"E");
        }
    }

    public static Word loads(String text){
        Word word=new Word();
        String nodes[]=text.split("=");
        if(nodes==null){
            return null;
        }else if(nodes.length!=3){
            return null;
        }else{
            word.name=nodes[0];
            word.translated=nodes[1].replace("#gap#", "\n");
            word.chinese = nodes[2].equals("C");
            return word;
        }
    }

    public static Word matchOnline(String word){
        Word matchedWord = new Word();

        //translate
        String APIHead = "http://dict.youdao.com/jsonapi?jsonversion=2&client=mobile&q=";
        String APITail = "&dicts=%7B%22count%22%3A99%2C%22dicts%22%3A%5B%5B%22ec%22%2C%22ce%22%2C%22newcj%22%2C%22newjc%22%2C%22kc%22%2C%22ck%22%2C%22fc%22%2C%22cf%22%2C%22multle%22%2C%22jtj%22%2C%22pic_dict%22%2C%22tc%22%2C%22ct%22%2C%22typos%22%2C%22special%22%2C%22tcb%22%2C%22baike%22%2C%22lang%22%2C%22simple%22%2C%22wordform%22%2C%22exam_dict%22%2C%22ctc%22%2C%22web_search%22%2C%22auth_sents_part%22%2C%22ec21%22%2C%22phrs%22%2C%22input%22%2C%22wikipedia_digest%22%2C%22ee%22%2C%22collins%22%2C%22ugc%22%2C%22media_sents_part%22%2C%22syno%22%2C%22rel_word%22%2C%22longman%22%2C%22ce_new%22%2C%22le%22%2C%22newcj_sents%22%2C%22blng_sents_part%22%2C%22hh%22%5D%2C%5B%22ugc%22%5D%2C%5B%22longman%22%5D%2C%5B%22newjc%22%5D%2C%5B%22newcj%22%5D%2C%5B%22web_trans%22%5D%2C%5B%22fanyi%22%5D%5D%7D&keyfrom=mdict.7.2.0.android&model=honor&mid=5.6.1&imei=659135764921685&vendor=wandoujia&screen=1080x1800&ssid=superman&network=wifi&abtest=2&xmlVersion=5.1";
        if(!word.equals("")){
            String api = APIHead + word.replace(" ", "%20") + APITail;
            try{
                URL url = new URL(api);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.getInputStream();
                String result = IOUtils.readString(connection.getInputStream());
                if(result==null){
                    return null;
                }
                matchedWord.translated=getTranslated(result);
            } catch (Exception e){
                HomeActivity.instance.showMessage(e.toString());
                return null;
            }

        }
        else{
            return null;
        }

        matchedWord.name=word;
        if(matchedWord.name==null || matchedWord.translated==null){
            return null;
        }
        return matchedWord;
    }

    private static String getTranslated(String jsonString) {
        try{
            //IOUtils.println(jsonString);
            JSONArray matches = JSONObject.parseObject(jsonString)
                    .getJSONObject("ec")
                    .getJSONArray("word");
            if (matches.size() == 0) {
                return null;
            } else {
                JSONArray subItems = matches
                        .getJSONObject(0)
                        .getJSONArray("trs");
                String parsed = "";
                int i = 0;
                while (i < subItems.size()) {
                    if (!parsed.equals("")) {
                        parsed += "\n";
                    }
                    String subText = subItems.getJSONObject(i)
                            .getJSONArray("tr")
                            .getJSONObject(0)
                            .getJSONObject("l")
                            .getJSONArray("i").getString(0);
                    parsed += subText;
                    i++;
                }
                return parsed;
            }
        }catch(NullPointerException e){
            return null;
        }
    }


}
